import React from 'react';
import menuRoute from 'routes/menuRoute'
import {deepCopy, deepFullCopy, messages} from 'share/common'
import {Form, Affix, Button, Modal, Spin, message, Tree,} from 'antd'
const TreeNode = Tree.TreeNode;
import documentService from 'containers/setting/help-document-management/help-document.service'
import 'braft-editor/dist/braft.css'
import 'styles/setting/help-document-management/help-document-edit.scss'
import { connect } from 'react-redux'
import TitleAndContentI18n from "components/template/title-and-content-i18n/title-and-content-i18n";

class HelpDocumentEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      saveLoading: false,
      prodListLoading: false,
      fileUploadVisible: false,
      linkDocVisible: false,
      info: {i18n: {docTitle: [], docContent: []},},
      language: 'zh_cn',
      chapterNames: [], //章节名称
      i18n: {title: [], content: []},
    }
  }

  componentWillMount() {
    this.getMenuList();
    this.getInfo()
  }

  //获取目录列表
  getMenuList = () => {
    documentService.getDocumentMenu().then(res => {
      this.getChapterNames(res.data)
    })
  };

  //获取章节路径
  getChapterNames = (items) => {
    let list = [];
    let chapterNames = [];
    let getMenuList = arr => {
      arr.map(item => {
        list.push(item);
        item.children && getMenuList(item.children)
      })
    };
    getMenuList(items);
    let getParentIDList = id => {
      if (id && id !== '0') { //非一级目录
        list.map(item => {
          if (item.id === id) {
            chapterNames.push(item.docTitle);
            getParentIDList(item.parentId)
          }
        })
      }
    };
    getParentIDList(this.props.params.id);
    chapterNames.reverse();
    this.setState({ chapterNames })
  };

  getInfo = () => {
    let historyID = this.props.params.historyID;
    const {i18n} = this.state;
    historyID = historyID === ":historyID" ? "" : historyID;
    let id = historyID || this.props.params.id;
    this.setState({ loading: true });
    let params = historyID ? {historyId: id} : id;
    documentService[historyID ? 'getHistoryContent' : 'getDocumentInfo'](params).then(res => {
      if(res.data.i18n){
        res.data.i18n.docContent = res.data.i18n.docContent.map(item => {
          return {
            language: item.language,
            value: this.transformChar(item.value)
          }
          }
        );
        i18n.title = res.data.i18n.docTitle;
        i18n.content = res.data.i18n.docContent;
      }
      this.setState({
        i18n: deepCopy(i18n),
        loading: false,
        info: res.data,
      });
      this.props.onMenuSelect(res.data)
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  transformChar = (str) => {
    return str ? str.replace(/﹤/g, "<").replace(/﹥/g, ">") : "";
  };

  handleSave = () => {
    const {info} = this.state;
    let bool = info.i18n.docTitle.some(item =>
      item.value.length > 200
    );
    if(bool){
      message.warning(messages('basic-11.key135')/*标题不能超过200个字符*/);
      return
    }
    Modal.confirm({
      title: messages('basic-11.key136')/*确定要保存吗？*/,
      content: messages('basic-11.key137')/*保存后，点击【内容更新到操作手册】按钮，该版本会覆盖之前的内容成为最新版本*/,
      onOk: () => {
        let params = Object.assign({}, info);
        params.i18n.docTitle.forEach(item => {
          if(item.language.toLowerCase() === this.props.language.code.toLowerCase()){
            params.docTitle = item.value;
            let con = params.i18n.docContent.filter(ans => ans.language === item.language)[0];
            params.docContent = con ? con.value : "";
          }
        });
        if (params.sourceId) {
          params.id = params.sourceId;
          delete params.sourceId;
        }
        if (params.sourceParentId) {
          params.parentId = params.sourceParentId;
          delete params.sourceParentId;
        }
        this.setState({ saveLoading: true });
        documentService.editDocument(params, 'put').then(() => {
          message.success('保存成功');
          this.context.router.push(menuRoute.getPageUrlByKey('help-document-management'))
        }).catch(() => {
          this.setState({ saveLoading: false })
        })
      }
    })
  };

  goBack = () => {
    Modal.confirm({
      title: messages('basic-11.key138')/*确定要返回吗？*/,
      content: messages('basic-11.key139')/*返回后，本次修改将会丢失*/,
      onOk: () => {
        window.history.back(-1);
      }
    })
  };

  //渲染章节路径
  renderChapterRouter = () => {
    const chapterNames = deepFullCopy(this.state.chapterNames);
    let current = chapterNames.splice(chapterNames.length - 1, 1);
    return (
      <div style={{display: 'inline-block'}}>
        {chapterNames.join(' - ')}
        {chapterNames.length ? ' - ' : ''}
        <span>{current[0]}</span>
      </div>
    )
  };

  //渲染目录树
  renderTree = (data) => {
    return data.map(item => {
      return (
        <TreeNode key={item.id} title={item.docTitle}>
          {item.children && item.children.length ? this.renderTree(item.children) : ''}
        </TreeNode>
      )
    })
  };

  handleTabChange = (activeTab) => {
    this.setState({activeTab});
  };

  onI18nChange = (i18n) => {
    const {info} = this.state;
    info.i18n.docTitle = i18n.title;
    info.i18n.docContent = i18n.content;
    this.setState({ info })
  };

  render() {
    const { loading, saveLoading, i18n } = this.state;
    const {authPolicyAll} = this.props;
    return (
      <div className="help-document-edit">
        <Spin spinning={loading}>
          <div className="title-path-area">
            {this.renderChapterRouter()}
          </div>
          <div className="f-left" style={{color: 'rgba(0, 0, 0, 0.85)', fontSize: 14}}>
            <span style={{color: 'red'}}>*&nbsp;</span>{messages('basic-11.key115')/*标题及正文*/}：
          </div>
          <div className="f-right"  style={{marginBottom: 100, maxWidth: "calc(100% - 100px)"}}>
            <TitleAndContentI18n onI18nChange={this.onI18nChange} i18n={i18n}/>
          </div>
        </Spin>

        <Affix className="bottom-bar" offsetBottom={0}>
          <Button type="primary" loading={saveLoading} onClick={this.handleSave} disabled={!authPolicyAll}>
            {messages('common.save')/*保存*/}
          </Button>
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

HelpDocumentEdit.contextTypes = {
  router: React.PropTypes.object
};

HelpDocumentEdit.propTypes = {};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    authPolicyAll: state.main.authPolicyAll,
  }
}

const WrappedHelpDocumentEdit = Form.create()(HelpDocumentEdit);
export default connect(mapStateToProps)(WrappedHelpDocumentEdit);
